package com.example.demo.tp;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExample {

    public static void main(String[] args) throws InterruptedException {
//        t1();
        t2();
    }

    private static void t1() throws InterruptedException {
        // 创建一个包含 10 个线程的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // 创建一个包含 10000 个元素的 List
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10001; i++) {
            list.add(i);
        }

        // 将 List 分成 10 个子 List，每个子 List 包含 1000 个元素
        List<List<Integer>> subLists = new ArrayList<>();
        int subListSize = 1000;
        for (int i = 0; i < list.size(); i += subListSize) {
            List<Integer> integers = list.subList(i, Math.min(i + subListSize, list.size()));
            subLists.add(integers);
        }

        // 提交每个子 List 的处理任务给线程池
        for (List<Integer> subList : subLists) {
            executorService.submit(new Task(subList));
        }

        // 等待线程池中所有任务执行完毕
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        // 打印处理结果
        System.out.println("List size: " + list.size());
        System.out.println("Sum of elements: " + Task.getSum());
    }

    private static void t2() {
        int totalSize = 71;
        int threadSiz = 20;
        //每个线程工作的元素
        int subListSize = totalSize / threadSiz;
        //线程数 totalSize/subListSize =200/10
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < totalSize; i++) {
            list.add(i);
        }

        List<List<Integer>> subLists = new ArrayList<>();


        for (int i = 0; i < list.size(); i += subListSize) {
            subLists.add(list.subList(i, Math.min(i + subListSize, list.size())));
        }
        System.out.println(222);

    }

    static class Task implements Runnable {
        private List<Integer> list;
        private static long sum = 0;

        public Task(List<Integer> list) {
            this.list = list;
        }

        @Override
        public void run() {
            long subSum = 0;
            for (int i : list) {
                subSum += i;
            }
            synchronized (Task.class) {
                sum += subSum;
            }
        }

        public static long getSum() {
            return sum;
        }
    }
}